package com.crm.service;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.crm.dao.OfferDAO;
import com.crm.po.Offer;
import com.crm.common.CrmInit;
import com.crm.util.DateEx;
import com.crm.util.FileEx;
import com.crm.util.RequestEx;

public class OfferService {
	
	private static Logger logger = Logger.getLogger(OfferService.class);
	
	public Map<String, Object> getOffers(HttpServletRequest request){
		StringBuffer Hql = new StringBuffer(" from Offer t where 1=1 ");
		int page = Integer.parseInt(request.getParameter("page"));//当前第几页
		int rows = Integer.parseInt(request.getParameter("rows"));//每页显示几行

		String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
		String islive = RequestEx.getStringTrim(request.getParameter("islive"));
		String name = RequestEx.getStringTrim(request.getParameter("name"));
		String remark = RequestEx.getStringTrim(request.getParameter("remark"));

		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.CGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		if(name != null && name.trim().length() > 0){
			Hql.append(" and t.name like '%");
			Hql.append(name);
			Hql.append("%' ");
		}
		if(remark != null && remark.trim().length() > 0){
			Hql.append(" and t.remark like '%");
			Hql.append(remark);
			Hql.append("%' ");
		}
		
		OfferDAO dao = new OfferDAO();
		String countHql = "select count(t.tid) " + Hql.toString();
		int count = dao.getCount(countHql);
		Hql.append(" order by t.creattime desc ");
	    List<Offer> list = dao.offerListPage(Hql.toString(), (page-1) * rows, rows);
	    
	    Map<String, Object> map = new HashMap<String, Object>();
	    map.put("count", count);
	    map.put("rows", list);
	    
	    return map;
	} 
	
	public int getOfferCountByTreeid(String treeid, String islive){
		StringBuffer Hql = new StringBuffer(" from Offer t where 1=1 ");

		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.CGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		
		OfferDAO dao = new OfferDAO();
		String countHql = "select count(t.tid) " + Hql.toString();
		int count = dao.getCount(countHql);
	    
	    return count;
	} 
	
	public boolean saveOrUpdateOffer(HttpServletRequest request){
		try{
			
			String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
			
			String tid = RequestEx.getStringTrim(request.getParameter("tid"));
			String name = RequestEx.getStringTrim(request.getParameter("name"));
			String path = RequestEx.getStringTrim(request.getParameter("fileName"));
			String remark = RequestEx.getStringTrim(request.getParameter("remark"));
			
			OfferDAO dao = new OfferDAO();
			Offer offer = null;
			if(tid != null && tid.trim().length() > 0){
				offer = dao.findById(tid);
				if(path != null && path.length() > 0 && !path.equals(offer.getPath())){
					FileEx.deleteFile(new File(CrmInit.UPLOAD_PATH + File.separatorChar + offer.getPath()));
					offer.setPath(path);
				}
			}else{				
				offer = new Offer();
				offer.setPath(path);
				offer.setCreattime(DateEx.getCurDatetimeAsLong());
				offer.setCreater(RequestEx.getCurUser(request).getUsername());
			}
			offer.setName(name);

			offer.setCGroup(treeid);
			offer.setRemark(remark);
			offer.setIslive("Y");
			
			offer.setUpdatetime(DateEx.getCurDatetimeAsLong());
			offer.setUpdater(RequestEx.getCurUser(request).getUsername());
			
			dao.saveOrUpdate(offer);
		}catch(Exception e){
			logger.error("save or update offer fail:", e);
			return false;
		}
	    return true;
	}
	
	public boolean deleteOffers(HttpServletRequest request){
		int result = 0;
		try{
			String tids = RequestEx.getStringTrim(request.getParameter("tids"));
			if(tids.length() > 0){
				String hql = "UPDATE Offer T SET T.islive = 'N' WHERE T.tid IN (" + tids + ")";
				OfferDAO dao = new OfferDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("delete offer fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean recoverOffers(HttpServletRequest request){
		int result = 0;
		try{
			String tids = RequestEx.getStringTrim(request.getParameter("tids"));
			if(tids.length() > 0){
				String hql = "UPDATE Offer T SET T.islive = 'Y' WHERE T.tid IN (" + tids + ")";
				OfferDAO dao = new OfferDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("recover offer fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean reallyDeleteOffers(HttpServletRequest request){
		int result = 0;
		try{
			String tids = RequestEx.getStringTrim(request.getParameter("tids"));
			if(tids.length() > 0){
				OfferDAO dao = new OfferDAO();
				List offers = dao.findList("from Offer T where 1=1 AND T.tid IN (" + tids + ")");
				if(offers != null && offers.size() > 0){
					Offer offer = null;
					for(int i = 0; i < offers.size(); i ++){
						offer = (Offer) offers.get(i);
						FileEx.deleteFile(new File(CrmInit.UPLOAD_PATH + File.separatorChar + offer.getPath()));
						dao.delete(offer);
						result ++;
					}
				}
			}			
		}catch(Exception e){
			logger.error("really delete offer fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public String upload(HttpServletRequest request){
		String returnFileName = "";
		try{
			boolean isMultipart= ServletFileUpload.isMultipartContent(request);  
	        if(isMultipart){  
	            //构造一个文件上传处理对象  
	            FileItemFactory factory = new DiskFileItemFactory();  
	            ServletFileUpload upload = new ServletFileUpload(factory);  
	  
	            Iterator items = null;  
                items = upload.parseRequest(request).iterator();  
                while(items.hasNext()){  
                    FileItem item = (FileItem) items.next();  
                    if(!item.isFormField()){  
                        //取出上传文件的文件名称  
                        String name = item.getName();
                        if(name == null || name.length() == 0){
                        	continue;
                        }
                        //取得上传文件以后的存储路径  
                        String fileName = name.substring(name.lastIndexOf('\\') + 1, name.length());  
                        //上传文件以后的存储路径  
                        
                        String saveDir = CrmInit.UPLOAD_PATH;  
                        if (!(new File(saveDir).isDirectory())){  
                            new File(saveDir).mkdir();  
                        }  
                        returnFileName = DateEx.getCurDatetimeAsLong() + "-" +fileName;
                        String path= saveDir + File.separatorChar + returnFileName;  
  
                        //上传文件  
                        File uploaderFile = new File(path);  
                        item.write(uploaderFile);  
                    }  
                }                               
	        }   
		}catch(Exception e){
			logger.error("really delete offer fail:", e);
			return "error";
		}
	    return returnFileName;
	}
	
	
	public static void main(String[] args){

	}
	
}
